﻿namespace Hidistro.UI.Web
{
    using Hidistro.Core;
    using Hidistro.Entities.Commodities;
    using Hidistro.Entities.Orders;
    using Hidistro.Entities.Promotions;
    using Hidistro.Entities.Sales;
    using Hidistro.Membership.Context;
    using Hidistro.SaleSystem.Catalog;
    using Hidistro.SaleSystem.Member;
    using Hishop.Plugins;
    using System;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using Hishop.Plugins.Payment.ChinaUnionPay;
    using System.Configuration;
    using System.Text;
    using System.Web.Configuration;
    using System.IO;
    using System.Collections.Generic;

    public class SendPayment : Page
    {
        protected HtmlForm form1;

        private OrderInfo GetOrderInfo(string orderId)
        {
            Juse.Interface.UserOrder uo = new Juse.Interface.UserOrder();
            if (orderId.Length == 11)
            {
                orderId = uo.GetUserMaxOrderId(orderId);
            }
            JSShop.Model.Hishop_Orders ho = new JSShop.Model.Hishop_Orders();
            ho = uo.GetModelByOrderId(orderId);
            IList<JSShop.Model.Hishop_OrderItems> listhoi = uo.GetItemsByOrderId(orderId);
            IList<JSShop.Model.Hishop_OrderGifts> listhog = uo.GetOrderGiftList(orderId);

            if (ho != null)
            {
                OrderInfo info = new OrderInfo();
                info = PopulateOrder(ho);
                Juse.Interface.ProductBrowser pb = new Juse.Interface.ProductBrowser();
                Juse.Interface.CategoryBrowser cb = new Juse.Interface.CategoryBrowser();
                foreach (JSShop.Model.Hishop_OrderItems item in listhoi)
                {
                    LineItemInfo itemInfo = PopulateLineItem(item);
                    //获取商品信息
                    JSShop.Model.Hishop_Products hp = pb.GetProductInfo(itemInfo.ProductId);
                    itemInfo.ProductCode = hp.ProductCode;//商品代码赋值
                    //获取分类
                    JSShop.Model.Hishop_Categories hc = cb.GetCategoryInfo(hp.CategoryId);
                    itemInfo.CategoryUrl = hc.RewriteName;
                    info.LineItems.Add(itemInfo.SkuId, itemInfo);
                }
                foreach (JSShop.Model.Hishop_OrderGifts item in listhog)
                {
                    OrderGiftInfo giftInfo = PopulateOrderGift(item);
                    info.Gifts.Add(giftInfo);
                }

                return info;
            }

            return null;
        }
        public static OrderGiftInfo PopulateOrderGift(JSShop.Model.Hishop_OrderGifts reader)
        {
            if (null == reader)
            {
                return null;
            }
            return new OrderGiftInfo { OrderId = (string)reader.OrderId, GiftId = (int)reader.GiftId, GiftName = (string)reader.GiftName, CostPrice = (reader.CostPrice.HasValue) ? 0M : ((decimal)reader.CostPrice), ThumbnailsUrl = reader.ThumbnailsUrl, Quantity = (reader.Quantity.HasValue) ? 0 : ((int)reader.Quantity), PromoteType = (int)reader.PromoType };
        }

        public OrderInfo PopulateOrder(JSShop.Model.Hishop_Orders reader)
        {
            if (reader == null)
            {
                return null;
            }
            OrderInfo info = new OrderInfo
            {
                OrderId = (string)reader.OrderId
            };
            if (null != reader.GatewayOrderId)
            {
                info.GatewayOrderId = (string)reader.GatewayOrderId;
            }
            if (null != reader.Remark)
            {
                info.Remark = (string)reader.Remark;
            }
            if (null != reader.ManagerMark)
            {
                info.ManagerMark = new OrderMark?((OrderMark)reader.ManagerMark);
            }
            if (null != reader.ManagerRemark)
            {
                info.ManagerRemark = (string)reader.ManagerRemark;
            }
            if (null != reader.AdjustedDiscount)
            {
                info.AdjustedDiscount = (decimal)reader.AdjustedDiscount;
            }
            if (null != reader.OrderStatus)
            {
                info.OrderStatus = (OrderStatus)reader.OrderStatus;
            }
            if (null != reader.CloseReason)
            {
                info.CloseReason = (string)reader.CloseReason;
            }
            if (null != reader.OrderPoint)
            {
                info.Points = (int)reader.OrderPoint;
            }
            info.OrderDate = (DateTime)reader.OrderDate;
            if (null != reader.PayDate)
            {
                info.PayDate = (DateTime)reader.PayDate;
            }
            if (null != reader.ShippingDate)
            {
                info.ShippingDate = (DateTime)reader.ShippingDate;
            }
            if (null != reader.FinishDate)
            {
                info.FinishDate = (DateTime)reader.FinishDate;
            }
            info.UserId = (int)reader.UserId;
            info.Username = (string)reader.Username;
            if (null != reader.EmailAddress)
            {
                info.EmailAddress = (string)reader.EmailAddress;
            }
            if (null != reader.RealName)
            {
                info.RealName = (string)reader.RealName;
            }
            if (null != reader.QQ)
            {
                info.QQ = (string)reader.QQ;
            }
            if (null != reader.Wangwang)
            {
                info.Wangwang = (string)reader.Wangwang;
            }
            if (null != reader.MSN)
            {
                info.MSN = (string)reader.MSN;
            }
            if (null != reader.ShippingRegion)
            {
                info.ShippingRegion = (string)reader.ShippingRegion;
            }
            if (null != reader.Address)
            {
                info.Address = (string)reader.Address;
            }
            if (null != reader.ZipCode)
            {
                info.ZipCode = (string)reader.ZipCode;
            }
            if (null != reader.ShipTo)
            {
                info.ShipTo = (string)reader.ShipTo;
            }
            if (null != reader.TelPhone)
            {
                info.TelPhone = (string)reader.TelPhone;
            }
            if (null != reader.CellPhone)
            {
                info.CellPhone = (string)reader.CellPhone;
            }
            if (null != reader.ShipToDate)
            {
                info.ShipToDate = (string)reader.ShipToDate;
            }
            if (null != reader.ShippingModeId)
            {
                info.ShippingModeId = (int)reader.ShippingModeId;
            }
            if (null != reader.ModeName)
            {
                info.ModeName = (string)reader.ModeName;
            }
            if (null != reader.RealShippingModeId)
            {
                info.RealShippingModeId = (int)reader.RealShippingModeId;
            }
            if (null != reader.RealModeName)
            {
                info.RealModeName = (string)reader.RealModeName;
            }
            if (null != reader.RegionId)
            {
                info.RegionId = (int)reader.RegionId;
            }
            if (null != reader.Freight)
            {
                info.Freight = (decimal)reader.Freight;
            }
            if (null != reader.AdjustedFreight)
            {
                info.AdjustedFreight = (decimal)reader.AdjustedFreight;
            }
            if (null != reader.ShipOrderNumber)
            {
                info.ShipOrderNumber = (string)reader.ShipOrderNumber;
            }
            if (null != reader.ExpressCompanyName)
            {
                info.ExpressCompanyName = (string)reader.ExpressCompanyName;
            }
            if (null != reader.ExpressCompanyAbb)
            {
                info.ExpressCompanyAbb = (string)reader.ExpressCompanyAbb;
            }
            if (null != reader.PaymentTypeId)
            {
                info.PaymentTypeId = (int)reader.PaymentTypeId;
            }
            if (null != reader.PaymentType)
            {
                info.PaymentType = (string)reader.PaymentType;
            }
            if (null != reader.PayCharge)
            {
                info.PayCharge = (decimal)reader.PayCharge;
            }
            if (null != reader.RefundStatus)
            {
                info.RefundStatus = (RefundStatus)reader.RefundStatus;
            }
            if (null != reader.RefundAmount)
            {
                info.RefundAmount = (decimal)reader.RefundAmount;
            }
            if (null != reader.RefundRemark)
            {
                info.RefundRemark = (string)reader.RefundRemark;
            }
            if (null != reader.Gateway)
            {
                info.Gateway = (string)reader.Gateway;
            }
            if (null != reader.ReducedPromotionId)
            {
                info.ReducedPromotionId = (int)reader.ReducedPromotionId;
            }
            if (null != reader.ReducedPromotionName)
            {
                info.ReducedPromotionName = (string)reader.ReducedPromotionName;
            }
            if (null != reader.ReducedPromotionAmount)
            {
                info.ReducedPromotionAmount = (decimal)reader.ReducedPromotionAmount;
            }
            if (null != reader.IsReduced)
            {
                info.IsReduced = (bool)reader.IsReduced;
            }
            if (null != reader.SentTimesPointPromotionId)
            {
                info.SentTimesPointPromotionId = (int)reader.SentTimesPointPromotionId;
            }
            if (null != reader.SentTimesPointPromotionName)
            {
                info.SentTimesPointPromotionName = (string)reader.SentTimesPointPromotionName;
            }
            if (null != reader.IsSendTimesPoint)
            {
                info.IsSendTimesPoint = (bool)reader.IsSendTimesPoint;
            }
            if (null != reader.TimesPoint)
            {
                info.TimesPoint = (decimal)reader.TimesPoint;
            }
            if (null != reader.FreightFreePromotionId)
            {
                info.FreightFreePromotionId = (int)reader.FreightFreePromotionId;
            }
            if (null != reader.FreightFreePromotionName)
            {
                info.FreightFreePromotionName = (string)reader.FreightFreePromotionName;
            }
            if (null != reader.IsFreightFree)
            {
                info.IsFreightFree = (bool)reader.IsFreightFree;
            }
            if (null != reader.CouponName)
            {
                info.CouponName = (string)reader.CouponName;
            }
            if (null != reader.CouponCode)
            {
                info.CouponCode = (string)reader.CouponCode;
            }
            if (null != reader.CouponAmount)
            {
                info.CouponAmount = (decimal)reader.CouponAmount;
            }
            if (null != reader.CouponValue)
            {
                info.CouponValue = (decimal)reader.CouponValue;
            }
            if (null != reader.GroupBuyId)
            {
                info.GroupBuyId = (int)reader.GroupBuyId;
            }
            if (null != reader.CountDownBuyId)
            {
                info.CountDownBuyId = (int)reader.CountDownBuyId;
            }
            if (null != reader.BundlingId)
            {
                info.BundlingID = (int)reader.BundlingId;
            }
            if (null != reader.BundlingPrice)
            {
                info.BundlingPrice = (decimal)reader.BundlingPrice;
            }
            if (null != reader.NeedPrice)
            {
                info.NeedPrice = (decimal)reader.NeedPrice;
            }
            if (null != reader.GroupBuyStatus)
            {
                info.GroupBuyStatus = (GroupBuyStatus)reader.GroupBuyStatus;
            }
            if (null != reader.TaobaoOrderId)
            {
                info.TaobaoOrderId = (string)reader.TaobaoOrderId;
            }
            if (null != reader.Tax)
            {
                info.Tax = (decimal)reader.Tax;
            }
            else
            {
                info.Tax = 0M;
            }
            if (null != reader.InvoiceTitle)
            {
                info.InvoiceTitle = (string)reader.InvoiceTitle;
            }
            else
            {
                info.InvoiceTitle = "";
            }
            return info;
        }
        public static LineItemInfo PopulateLineItem(JSShop.Model.Hishop_OrderItems reader)
        {
            if (null == reader)
            {
                return null;
            }
            LineItemInfo info = new LineItemInfo
            {
                SkuId = (string)reader.SkuId,
                ProductId = (int)reader.ProductId
            };
            if (reader.SKU != null)
            {
                info.SKU = (string)reader.SKU;
            }
            info.Quantity = (int)reader.Quantity;
            info.ShipmentQuantity = (int)reader.ShipmentQuantity;
            info.ItemCostPrice = (decimal)reader.CostPrice;
            info.ItemListPrice = (decimal)reader.ItemListPrice;
            info.ItemAdjustedPrice = (decimal)reader.ItemAdjustedPrice;
            info.ItemDescription = (string)reader.ItemDescription;
            if (reader.ThumbnailsUrl != null)
            {
                info.ThumbnailsUrl = (string)reader.ThumbnailsUrl;
            }
            //info.ItemWeight = (decimal)reader.Weight;
            if (null != reader.SKUContent)
            {
                info.SKUContent = (string)reader.SKUContent;
            }
            if (null != reader.PromotionId)
            {
                info.PromotionId = (int)reader.PromotionId;
            }
            if (null != reader.PromotionName)
            {
                info.PromotionName = (string)reader.PromotionName;
            }
            //if (null != reader["ProductCode"])
            //{
            //    info.ProductCode = (string)reader["ProductCode"];
            //}
            //if (null != reader["CategoryUrl"])
            //{
            //    info.CategoryUrl = (string)reader["CategoryUrl"];
            //}
            return info;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            string orderId = this.Page.Request.QueryString["orderId"];

            OrderInfo orderInfo = GetOrderInfo(orderId);//TradeHelper.GetOrderInfo(orderId);
            if (orderInfo == null)
            {
                base.Response.Write("<div><font color='red'>您要付款的订单已经不存在，请联系管理员确定</font></div>");
            }
            else if (orderInfo.OrderStatus != OrderStatus.WaitBuyerPay)
            {
                this.Page.Response.Write("订单当前状态不能支付");
            }
            else
            {
                if (orderInfo.CountDownBuyId > 0)
                {
                    CountDownInfo countDownInfoByCountDownId = ProductBrowser.GetCountDownInfoByCountDownId(orderInfo.CountDownBuyId);
                    if ((countDownInfoByCountDownId == null) || (countDownInfoByCountDownId.EndDate < DateTime.Now))
                    {
                        this.Page.Response.Write("此订单属于限时抢购类型订单，但限时抢购活动已经结束或不存在");
                        return;
                    }
                }
                //获取支付方式
                PaymentModeInfo paymentMode = TradeHelper.GetPaymentMode(orderInfo.PaymentTypeId);
                if (paymentMode == null)
                {
                    base.Response.Write("<div><font color='red'>您之前选择的支付方式已经不存在，请联系管理员修改支付方式</font></div>");
                }
                else
                {
                    foreach (LineItemInfo info4 in orderInfo.LineItems.Values)
                    {
                        ProductBrowseInfo info5 = ProductBrowser.GetProductBrowseInfo(info4.ProductId, 6, 6);
                        if ((info5.Product == null) || (info5.Product.SaleStatus == ProductSaleStatus.Delete))
                        {
                            base.Response.Redirect(Globals.ApplicationPath + "/ResourceNotFound.aspx?errorMsg=" + Globals.UrlEncode("订单内商品已经被管理员删除"));
                            return;
                        }
                        if (info5.Product.SaleStatus == ProductSaleStatus.OnStock)
                        {
                            base.Response.Redirect(Globals.ApplicationPath + "/ResourceNotFound.aspx?errorMsg=" + Globals.UrlEncode("订单内商品已入库"));
                            return;
                        }
                        int stock = info5.Product.Stock;
                        if (info4.ShipmentQuantity > stock)
                        {
                            base.Response.Redirect(Globals.ApplicationPath + "/ResourceNotFound.aspx?errorMsg=" + Globals.UrlEncode("订单内商品库存不足"));
                            return;
                        }
                    }
                    //string showUrl = Globals.GetSiteUrls().UrlData.FormatUrl("user_MyOrder");
                    //if (paymentMode.Gateway.ToLower() != "hishop.plugins.payment.podrequest")
                    //{
                    //    showUrl = base.Server.UrlEncode(string.Format("http://{0}/user//UserOrderDetail.aspx?OrderId={1}", base.Request.Url.Host, orderInfo.OrderId));
                    //}
                    string showUrl = "http://account.x-juse.com/user/MyOrder.aspx";
                    if (paymentMode.Gateway.ToLower() != "hishop.plugins.payment.podrequest")
                    {
                        showUrl = base.Server.UrlEncode(string.Format("http://account.x-juse.com/User/UserOrderDetail.aspx?OrderId={0}", orderInfo.OrderId));
                    }

                    if (string.Compare(paymentMode.Gateway, "Hishop.Plugins.Payment.BankRequest", true) == 0)
                    {
                        showUrl = Globals.FullPath(Globals.GetSiteUrls().UrlData.FormatUrl("bank_pay", new object[] { orderInfo.OrderId }));
                    }
                    if (string.Compare(paymentMode.Gateway, "Hishop.Plugins.Payment.AdvanceRequest", true) == 0)
                    {
                        showUrl = Globals.FullPath(Globals.GetSiteUrls().UrlData.FormatUrl("advance_pay", new object[] { orderInfo.OrderId }));
                    }
                    string attach = "";
                    HttpCookie cookie = HiContext.Current.Context.Request.Cookies["Token_" + HiContext.Current.User.UserId.ToString()];
                    if ((cookie != null) && !string.IsNullOrEmpty(cookie.Value))
                    {
                        attach = cookie.Value;
                    }
                    if (paymentMode.Gateway.ToLower() == "wp_bankunionrequest")
                    {
                       string backurl = ConfigurationManager.AppSettings["PayUrl"].ToString();
                        //前台
                       string retuurl = string.Format("http://{0}/pay/YL_OrderRet_url.aspx", backurl);
                        //后台
                       string noturl = string.Format("http://{0}/pay/YL_OrderRet_url.aspx", backurl);
                       
                        //StringBuilder str = new StringBuilder();
                        //str.Append("\r\n" + DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss"));
                        //str.Append("\r\n.支付信息：");
                        //string ip = "";
                        //if (Request.ServerVariables.Get("HTTP_X_FORWARDED_FOR") != null)
                        //{
                        //    ip = Request.ServerVariables.Get("HTTP_X_FORWARDED_FOR").ToString().Trim();
                        //}
                        //else
                        //{
                        //    ip = Request.ServerVariables.Get("Remote_Addr").ToString().Trim();
                        //}
                        //str.Append("\r\n\tIp:" + ip);
                        //str.Append("\r\n\t浏览器:" + Request.Browser.Browser.ToString());
                        //str.Append("\r\n\t浏览器版本:" + Request.Browser.MajorVersion.ToString());
                        //str.Append("\r\n\t操作系统:" + Request.Browser.Platform.ToString());
                        //str.Append("\r\n.支付银联返回后台URL：" + noturl);
                        //str.Append("\r\n\t页面：" + Request.Url.ToString());
                        //str.Append("\r\n--------------------------------------------------------------------------------------------------");
                        //string upLoadPath = WebConfigurationManager.AppSettings["PayLogPath"];
                        //if (!Directory.Exists(upLoadPath))
                        //{
                        //    Directory.CreateDirectory(upLoadPath);
                        //}
                        //string FileName;
                        //string[] flist = Directory.GetFiles(upLoadPath, DateTime.Now.ToString("yyyy.MM.dd") + "_?.log");
                        //if (flist != null && flist.Length > 0)
                        //{
                        //    FileName = upLoadPath + DateTime.Now.ToString("yyyy.MM.dd") + "_" + flist.Length.ToString() + ".log";
                        //    FileInfo fileInfo = new FileInfo(FileName);
                        //    if (fileInfo != null && fileInfo.Length >= 100 * 1024 * 1024)
                        //    {
                        //        FileName = upLoadPath + DateTime.Now.ToString("yyyy.MM.dd") + "_" + (flist.Length + 1).ToString() + ".log";
                        //    }
                        //}
                        //else
                        //{
                        //    FileName = upLoadPath + DateTime.Now.ToString("yyyy.MM.dd") + "_1.log";
                        //}
                        //File.AppendAllText(FileName, str.ToString(), Encoding.UTF8);
                        WP_Bank wb = new WP_Bank(orderInfo.OrderId, orderInfo.GetTotal(), "订单支付", "订单号-" + orderInfo.OrderId, orderInfo.EmailAddress, orderInfo.OrderDate, showUrl, retuurl, noturl, attach);
                        wb.SendRequest();
                    }
                    else
                    {
                        PaymentRequest.CreateInstance(paymentMode.Gateway, HiCryptographer.Decrypt(paymentMode.Settings), orderInfo.OrderId, orderInfo.GetTotal(), "订单支付", "订单号-" + orderInfo.OrderId, orderInfo.EmailAddress, orderInfo.OrderDate, showUrl, Globals.FullPath(Globals.GetSiteUrls().UrlData.FormatUrl("PaymentReturn_url", new object[] { paymentMode.Gateway })), Globals.FullPath(Globals.GetSiteUrls().UrlData.FormatUrl("PaymentNotify_url", new object[] { paymentMode.Gateway })), attach).SendRequest();

                    }

                }
            }
        }
    }
}

